﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using ChinaSoft.BLL;
using ChinaSoft.Model;

namespace Admin.Sys
{
    public partial class RolePermissions : System.Web.UI.Page
    {
        private BLL_tb_MidSoft_PowerList bllPowerList = new BLL_tb_MidSoft_PowerList();
        private BLL_tb_MidSoft_RoleHavePower bllRoleHavePower = new BLL_tb_MidSoft_RoleHavePower();
        private Model_tb_MidSoft_RoleHavePower modelRoleHavePower = new Model_tb_MidSoft_RoleHavePower();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    int roleId = ChinaSoft.Common.Input.SetInt(Request.QueryString["ID"]);
                    LoadRoleName(roleId);
                    LoadBasicPower();
                    int basicSelected=LoadPowerSelected(roleId,cblMKName);
                    if (basicSelected > 0)
                    {
                        LoadSubBoxList(cblMKName, cblCDName);
                        int subSelected = LoadPowerSelected(roleId, cblCDName);
                        if (subSelected > 0)
                        {
                            LoadSubBoxList(cblCDName, cbFunction);
                            LoadPowerSelected(roleId, cbFunction);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 加载角色名称
        /// </summary>
        /// <param name="RoleId"></param>
        private void LoadRoleName(int RoleId)
        {
            BLL_tb_MidSoft_Roles bllRoles = new BLL_tb_MidSoft_Roles();
            Model_tb_MidSoft_Roles modelRoles = new Model_tb_MidSoft_Roles();
            modelRoles = bllRoles.GetModel(RoleId);
            if (modelRoles != null && !string.IsNullOrEmpty(modelRoles.RoleName))
                lblRoleName.Text = modelRoles.RoleName;
        }
        /// <summary>
        /// 加载权限的根目录(模块)
        /// </summary>
        private void LoadBasicPower()
        {
            BLL_tb_MidSoft_PowerList bllPowerList = new BLL_tb_MidSoft_PowerList();
            this.cblMKName.DataSource = bllPowerList.GetList("FatherID=0 or FatherID Is Null");
            this.cblMKName.DataBind();
        }
        /// <summary>
        /// 根据角色ID判断用户所选的根目录，如果有选中的则>0，否则=0
        /// </summary>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        private int LoadPowerSelected(int RoleId,CheckBoxList cboxList)
        {
            int count = 0;
            DataTable DT = new DataTable();
            DT = bllRoleHavePower.GetList("RoleId=" + RoleId + " order by RoleHavePowerId desc").Tables[0];
            for (int i = 0; i < cboxList.Items.Count; i++)
            {
                for (int mki = 0; mki < DT.Rows.Count; mki++)
                {
                    if (cboxList.Items[i].Value.Trim() == DT.Rows[mki]["PowerId"].ToString().Trim())
                    {
                        cboxList.Items[i].Selected = true;
                        count = count + 1;
                    }
                }
            }
            return count;
        }
        /// <summary>
        /// 加载子集的checkboxlist控件
        /// </summary>
        /// <param name="basiccboxList"></param>
        /// <param name="subboxList"></param>
        private void LoadSubBoxList(CheckBoxList basiccboxList,CheckBoxList subboxList)
        {
            string SQLString = string.Empty;
            int MKCount = 0;

            for (int i = 0; i < basiccboxList.Items.Count; i++)
            {
                if (basiccboxList.Items[i].Selected)
                {
                    MKCount = MKCount + 1;
                    if (MKCount == 1)
                        SQLString += " FatherID=" + basiccboxList.Items[i].Value;
                    else
                        SQLString += " OR FatherID=" + basiccboxList.Items[i].Value;
                }
            }
            subboxList.DataSource = bllPowerList.GetList(SQLString);
            subboxList.DataBind();
        }
        public struct DataCollectiveQX
        {
            public int CountMK;
            public int CountCD;
            public string[] MKID;
            public string[] CDID;
        }
        private DataCollectiveQX RecordRoleSet(CheckBoxList basicboxList,CheckBoxList subboxList)
        {
            DataCollectiveQX DColl = new DataCollectiveQX();
            DColl.CountMK = 0;
            DColl.CountCD = 0;
            DColl.MKID = new string[basicboxList.Items.Count];
            DColl.CDID = new string[subboxList.Items.Count];

            for (int i = 0; i < basicboxList.Items.Count; i++)
            {
                if (basicboxList.Items[i].Selected)
                {
                    DColl.MKID[DColl.CountMK] = basicboxList.Items[i].Value.Trim();
                    DColl.CountMK = DColl.CountMK + 1;
                }
            }

            for (int i = 0; i < subboxList.Items.Count; i++)
            {
                if (subboxList.Items[i].Selected)
                {
                    DColl.CDID[DColl.CountCD] = subboxList.Items[i].Value.Trim();
                    DColl.CountCD = DColl.CountCD + 1;
                }
            }

            return DColl;
        }
        /// <summary>
        /// 加载子集元素
        /// </summary>
        /// <param name="basicboxList"></param>
        /// <param name="subboxList"></param>
        private void LoadSubBoxListData(CheckBoxList basicboxList,CheckBoxList subboxList)
        {
            string SQLString = null;
            int ItemCount = 0;
            for (int i = 0; i < basicboxList.Items.Count; i++)
            {
                if (basicboxList.Items[i].Selected)
                {
                    ItemCount = ItemCount + 1;
                    if (ItemCount == 1)
                        SQLString += " FatherID = " + basicboxList.Items[i].Value.Trim();
                    else
                        SQLString += " OR FatherID = " + basicboxList.Items[i].Value.Trim();
                }
            }
            if (ItemCount > 0)
            {
                subboxList.DataSource = bllPowerList.GetList(SQLString);
                subboxList.DataBind();
            }
            else
            {
                subboxList.DataSource = bllPowerList.GetList(" FatherID=-1");
                subboxList.DataBind();
            }
        }
        /// <summary>
        /// 根据
        /// </summary>
        /// <param name="dcoll"></param>
        /// <param name="cboxList"></param>
        private void PowerSelected(DataCollectiveQX dcoll, CheckBoxList cboxList, bool result)
        {
            for (int i = 0; i < dcoll.CountCD; i++)
            {
                for (int cdI = 0; cdI < cblCDName.Items.Count; cdI++)
                {
                    if (cboxList.Items[cdI].Value == dcoll.CDID[i].Trim())
                        cboxList.Items[cdI].Selected = result;
                }
            }
        }
        /// <summary>
        /// 根目录（模块）全选按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtAllMK_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cblMKName.Items.Count; i++)
            {
                cblMKName.Items[i].Selected = true;
            }

            DataCollectiveQX DColl = RecordRoleSet(cblMKName,cblCDName);
            LoadSubBoxListData(cblMKName, cblCDName);
            PowerSelected(DColl, cblCDName,true);

            for (int i = 0; i < cblCDName.Items.Count; i++)
            {
                cblCDName.Items[i].Selected = true;
            }
            DColl = RecordRoleSet(cblCDName, cbFunction);
            LoadSubBoxListData(cblCDName, cbFunction);
            PowerSelected(DColl, cbFunction,true);
        }

        /// <summary>
        /// 菜单根目录（模块）取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtESCMK_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cblMKName.Items.Count; i++)
            {
                cblMKName.Items[i].Selected = false;
            }

            DataCollectiveQX DColl = RecordRoleSet(cblMKName, cblCDName);
            LoadSubBoxListData(cblMKName, cblCDName);
            PowerSelected(DColl, cblCDName, false);

            for (int i = 0; i < cblCDName.Items.Count; i++)
            {
                cblCDName.Items[i].Selected = true;
            }
            DColl = RecordRoleSet(cblCDName, cbFunction);
            LoadSubBoxListData(cblCDName, cbFunction);
            PowerSelected(DColl, cbFunction, false);
        }
        /// <summary>
        /// 二级菜单的全选按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtAllCD_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cblCDName.Items.Count; i++)
            {
                cblCDName.Items[i].Selected = true;
            }
            DataCollectiveQX DColl = RecordRoleSet(cblCDName, cbFunction);
            LoadSubBoxListData(cblCDName, cbFunction);
            PowerSelected(DColl, cbFunction, true);
        }
        /// <summary>
        /// 二级菜单的取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtESCCD_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cblCDName.Items.Count; i++)
            {
                cblCDName.Items[i].Selected = true;
            }
            DataCollectiveQX DColl = RecordRoleSet(cblCDName, cbFunction);
            LoadSubBoxListData(cblCDName, cbFunction);
            PowerSelected(DColl, cbFunction, false);
        }
        /// <summary>
        /// 三级菜单的全选按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cblCDName.Items.Count; i++)
            {
                cbFunction.Items[i].Selected = true;
            }
        }
        /// <summary>
        /// 三级菜单的取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnCancel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cblCDName.Items.Count; i++)
            {
                cbFunction.Items[i].Selected = false;
            }
        }
        /// <summary>
        /// 当菜单根目录的选项发生变化时，触发该事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cblMKName_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataCollectiveQX DColl = RecordRoleSet(cblMKName,cblCDName);
            LoadSubBoxListData(cblMKName, cblCDName);
            PowerSelected(DColl, cblCDName, true);

            DColl = RecordRoleSet(cblCDName, cbFunction);
            LoadSubBoxListData(cblCDName,cbFunction);
            PowerSelected(DColl, cbFunction, true);
        }
        /// <summary>
        /// 当二级菜单的选项发生变化时，触发该事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cblCDName_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataCollectiveQX DColl = RecordRoleSet(cblCDName, cbFunction);
            LoadSubBoxListData(cblCDName, cbFunction);
            PowerSelected(DColl, cbFunction, true);
        }

        /// <summary>
        /// 保存所有数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SavePopedom_ServerClick(object sender, EventArgs e)
        {
            string SQLString = null;

            DataTable DT = new DataTable();
            ChinaSoft.BLL.Common.Bind bllBind = new ChinaSoft.BLL.Common.Bind();
            int RoleId = ChinaSoft.Common.Input.SetInt(Request.QueryString["id"]);
            //删除该角色以前的所有权限
            bllBind.DeleteList("tb_MidSoft_RoleHavePower", "RoleId", RoleId.ToString());

            for (int mkI = 0; mkI < cblMKName.Items.Count; mkI++)
            {
                if (this.cblMKName.Items[mkI].Selected)
                {
                    #region 添加权限
                    modelRoleHavePower.PowerId = ChinaSoft.Common.Input.SetInt(cblMKName.Items[mkI].Value);
                    modelRoleHavePower.RoleId = RoleId;
                    modelRoleHavePower.CreateTime = DateTime.Now;
                    modelRoleHavePower.CreateUserId = 0;
                    if (Session["currentUserID"] != null && Session["currentUserID"].ToString() != "")
                        modelRoleHavePower.CreateUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);

                    int RtnInsMKBool = bllRoleHavePower.Add(modelRoleHavePower);
                    #endregion
                    DT = bllPowerList.GetList("FatherID=" + this.cblMKName.Items[mkI].Value).Tables[0];
                    for (int dtI = 0; dtI < DT.Rows.Count; dtI++)
                    {
                        for (int cdI = 0; cdI < cblCDName.Items.Count; cdI++)
                        {
                            if (this.cblCDName.Items[cdI].Selected)
                            {
                                if (this.cblCDName.Items[cdI].Value == DT.Rows[dtI]["PowerId"].ToString())
                                {
                                    #region 添加权限
                                    modelRoleHavePower.PowerId = ChinaSoft.Common.Input.SetInt(cblCDName.Items[cdI].Value);
                                    modelRoleHavePower.RoleId = RoleId;
                                    modelRoleHavePower.CreateTime = DateTime.Now;
                                    modelRoleHavePower.CreateUserId = 0;
                                    if (Session["currentUserID"] != null && Session["currentUserID"].ToString() != "")
                                        modelRoleHavePower.CreateUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
                                    bllRoleHavePower.Add(modelRoleHavePower);
                                    #endregion
                                    DataTable DT2= bllPowerList.GetList("FatherID="+this.cblCDName.Items[cdI].Value).Tables[0];
                                    for (int dtI2 = 0; dtI2 < DT2.Rows.Count; dtI2++)
                                    {
                                        for (int functionI = 0; functionI < cbFunction.Items.Count; functionI++)
                                        {
                                            if (this.cbFunction.Items[functionI].Selected)
                                            {
                                                if (this.cbFunction.Items[functionI].Value == DT2.Rows[functionI]["PowerId"].ToString())
                                                {
                                                    #region 添加权限
                                                    modelRoleHavePower.PowerId = ChinaSoft.Common.Input.SetInt(cbFunction.Items[cdI].Value);
                                                    modelRoleHavePower.RoleId = RoleId;
                                                    modelRoleHavePower.CreateTime = DateTime.Now;
                                                    modelRoleHavePower.CreateUserId = 0;
                                                    if (Session["currentUserID"] != null && Session["currentUserID"].ToString() != "")
                                                        modelRoleHavePower.CreateUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
                                                    bllRoleHavePower.Add(modelRoleHavePower);
                                                    #endregion
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Response.Write("<script>alert('成功！');top.window.parent.frames.item('workspace').location.reload();window.parent.$('#DivSysiframe').dialog(\"close\");</script>");
        }
    }
}